<template>
  <div class="app-container" style="background: #FFFFFF;">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">


      <el-form-item label="业务员" prop="userId" v-hasPermi="['AgreementMain:agreement:bdsel']">

        <el-select v-model="queryParams.userId" style="width: 90%;" filterable placeholder="业务员" clearable>
          <el-option v-for="item in ywyOptions" :key="item.userId" :label="item.nickName"
            :value="item.userId.toString()"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="合同时间">

        <el-date-picker v-model="dateRange[0]" type="date" value-format="yyyy-MM-dd" placeholder="开始时间">
        </el-date-picker>

      </el-form-item>
      <el-form-item label="">
        <span>至</span>
      </el-form-item>
      <el-form-item label="">
        <el-date-picker v-model="dateRange[1]" type="date" value-format="yyyy-MM-dd" placeholder="结束时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="客户名称" prop="khname">
        <el-input v-model="queryParams.khname" placeholder="请输入客户名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="合同类型" prop="alltype">
        <el-select v-model="queryParams.alltype" style="width: 90%;" filterable placeholder="业务员" clearable>
          <el-option key="0" label="全部" value="0"></el-option>
          <el-option key="1" label="仅订单" value="1"></el-option>
          <el-option key="2" label="仅大客" value="2"></el-option>
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="合同时间">
        <el-date-picker v-model="dateRange" value-format="yyyy-MM-dd" type="daterange" range-separator="-"
          start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
      </el-form-item> -->

      <!-- <el-form-item label="" prop="other2">
        <el-checkbox v-model="checked">打款异常</el-checkbox>
      </el-form-item> -->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['AgreementMain:agreement:add']" v-if="false">新增</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini"
          @click="findkh(1, null, queryParams.pageNum)">添加合同</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-if="false" v-hasPermi="['AgreementMain:agreement:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['AgreementMain:agreement:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['AgreementMain:agreement:export']">导出</el-button>
      </el-col>

      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table border="" v-loading="loading" :data="agreementList" @selection-change="handleSelectionChange"
      :header-cell-style="{ background: '#eef1f6', color: '#606266' }" highlight-current-row class="abc"
      :row-class-name="tableAddClass">


      <el-table-column label="合同时间" align="center" prop="agrDate" width="100">
        <template slot-scope="scope">
          <div>{{ parseTime(scope.row.agrDate, "{y}-{m}-{d}") }}</div>
        </template>
      </el-table-column>
      <el-table-column label="合同编号" align="center" prop="agrId" width="140px">
        <template slot-scope="scope">
          <div v-if="scope.row.agrId.includes('X')" title="拨款单处生成" style="color: red;cursor:pointer;">{{ scope.row.agrId
            }}</div>
          <div v-else style="color: rgb(114, 175, 228);cursor:pointer;"
            @click="findkh(2, scope.row, queryParams.pageNum)">{{ scope.row.agrId }}
          </div>
        </template>
      </el-table-column>
      <el-table-column label="客户名称" align="left" prop="khname">
        <template slot-scope="scope">
          <div style="overflow: hidden; white-space: nowrap; text-overflow: ellipsis;" :title="scope.row.khname">
            {{ scope.row.khname }}</div>
        </template>
      </el-table-column>
      <el-table-column label="关联渠道" align="left" prop="gsname">
        <template slot-scope="scope">
          <div style="overflow: hidden; white-space: nowrap; text-overflow: ellipsis;" :title="scope.row.gsname">
            {{ scope.row.gsname }}</div>
        </template>
      </el-table-column>
      <el-table-column label="打款金额" align="right" prop="jeDk" />
      <el-table-column label="月返金额" align="center" prop="jeFdsj" v-if="false" />
      <el-table-column label="利润金额" align="center" prop="jeLrsj" v-if="false" />
      <!-- 原先的dkce不用了 -->

      <el-table-column label="分润金额" align="right" prop="outmoney"></el-table-column>
      <el-table-column label="已结算金额" align="right" prop="" width="100">
        <template slot-scope="scope">
          <div style=" color: rgb(23, 199, 7);">{{scope.row.jsMoney}}</div>
        </template>
      </el-table-column>
      <el-table-column label="未结算金额" align="right" prop="" width="100">
        <template slot-scope="scope">
          <div style=" color: red;">{{scope.row.noMoney}}</div>
        </template>
      </el-table-column>
      <el-table-column label="业务员" align="center" prop="ywyName" />



      </el-table-column>
      <!-- <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="160px" fixed="right">
        <template slot-scope="scope">
           <i class="el-icon-warning-outline" :title="'dd:'+scope.row.bkuserId+'\ndff'+scope.row.bkuserId" style="margin-right: 10px;color: #e4b52e;" v-else></i> 
          <el-button size="mini" type="text" icon="el-icon-edit" @click="findkh(2, scope.row, queryParams.pageNum)"
            >查看</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click.native.stop="handleDelete(scope.row)"
            v-hasPermi="['AgreementMain:agreement:remove']">删除</el-button>
        </template>
      </el-table-column> -->
    </el-table>

    <pagination v-show="total > 0" :page-sizes="[10, 20, 30, 50, 100]" :total="total" :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize" @pagination="getList" />

    <el-row style="margin-top: 25px;">
      <el-col :span="24">
        <el-card class="update-log">
          <div class="body">
            <el-row>
              <el-col :span="12" align="right">

                <p style="font-size: 18px; font-weight: bold;">

                </p>
              </el-col>
              <el-col :span="4" align="right">
                <h5 style="color: black; font-weight: bold;margin-top: 10px;margin-bottom: 0px;">分润金额</h5>
                <p style="font-size: 18px; font-weight: bold;color:cadetblue;">
                  {{ toFixed(jeform.amoney) }}
                </p>
              </el-col>
              <el-col :span="4" align="right">
                <h5 style="color: black; font-weight: bold;margin-top: 10px;margin-bottom: 0px;">已结算金额</h5>
                <p style="font-size: 18px; font-weight: bold;color:brown;">
                  {{ toFixed(jeform.bmoney) }}
                </p>
              </el-col>
              <el-col :span="4" align="right">
                <h5 style="color: black; font-weight: bold;margin-top: 10px;margin-bottom: 0px;">未结算金额</h5>
                <p style="font-size: 18px; font-weight: bold;color:blue;">
                  {{ toFixed(jeform.cmoney) }}
                </p>
              </el-col>


            </el-row>

          </div>
        </el-card>
      </el-col>
    </el-row>
    <!-- 添加或修改合同对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="客户id" prop="customerId">
          <el-input v-model="form.customerId" placeholder="请输入客户id" />
        </el-form-item>
        <el-form-item label="所属经销商ID" prop="deaId">
          <el-input v-model="form.deaId" placeholder="请输入所属经销商ID" />
        </el-form-item>
        <el-form-item label="实际归属渠道" prop="realDea">
          <el-input v-model="form.realDea" placeholder="请输入实际归属渠道" />
        </el-form-item>
        <el-form-item label="渠道业务员id" prop="userId">
          <el-input v-model="form.userId" placeholder="请输入渠道业务员id" />
        </el-form-item>
        <el-form-item label="合同时间" prop="agrDate">
          <el-input v-model="form.agrDate" placeholder="请输入合同时间" />
        </el-form-item>
        <el-form-item label="备用" prop="other1">
          <el-input v-model="form.other1" placeholder="请输入备用" />
        </el-form-item>
        <el-form-item label="备用" prop="other2">
          <el-input v-model="form.other2" placeholder="请输入备用" />
        </el-form-item>
        <el-form-item label="备用" prop="other3">
          <el-input v-model="form.other3" placeholder="请输入备用" />
        </el-form-item>
        <el-form-item label="备用" prop="other4">
          <el-input v-model="form.other4" placeholder="请输入备用" />
        </el-form-item>
        <el-form-item label="备用" prop="other5">
          <el-input v-model="form.other5" placeholder="请输入备用" />
        </el-form-item>
        <el-form-item label="打款金额" prop="jeDk">
          <el-input v-model="form.jeDk" placeholder="请输入打款金额" />
        </el-form-item>
        <el-form-item label="拨款金额" prop="jeBk">
          <el-input v-model="form.jeBk" placeholder="请输入拨款金额" />
        </el-form-item>
        <el-form-item label="月返点数" prop="jeFd">
          <el-input v-model="form.jeFd" placeholder="请输入月返点数" />
        </el-form-item>
        <el-form-item label="月实际返点数" prop="jeFdsj">
          <el-input v-model="form.jeFdsj" placeholder="请输入月实际返点数" />
        </el-form-item>
        <el-form-item label="季返点数" prop="jeJfd">
          <el-input v-model="form.jeJfd" placeholder="请输入季返点数" />
        </el-form-item>
        <el-form-item label="季返点实际" prop="jeJfdsj">
          <el-input v-model="form.jeJfdsj" placeholder="请输入季返点实际" />
        </el-form-item>
        <el-form-item label="暂估利润" prop="jeLr">
          <el-input v-model="form.jeLr" placeholder="请输入暂估利润" />
        </el-form-item>
        <el-form-item label="实际利润" prop="jeLrsj">
          <el-input v-model="form.jeLrsj" placeholder="请输入实际利润" />
        </el-form-item>
        <el-form-item label="返客金额" prop="jeFk">
          <el-input v-model="form.jeFk" placeholder="请输入返客金额" />
        </el-form-item>
        <el-form-item label="返渠金额" prop="jeFq">
          <el-input v-model="form.jeFq" placeholder="请输入返渠金额" />
        </el-form-item>
        <el-form-item label="月返比例" prop="jeYfbl">
          <el-input v-model="form.jeYfbl" placeholder="请输入月返比例" />
        </el-form-item>
        <el-form-item label="季返比例" prop="jeJfbl">
          <el-input v-model="form.jeJfbl" placeholder="请输入季返比例" />
        </el-form-item>
        <el-form-item label="年返比例" prop="jeNfbl">
          <el-input v-model="form.jeNfbl" placeholder="请输入年返比例" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 分配渠道弹窗测试 -->
    <el-dialog :title="titleqd" :visible.sync="openqd" width="1000px" append-to-body v-dialogDrag v-if="openqd">
      <el-form :model="queryParamsQd" ref="queryFormQd" size="small" :inline="true" label-width="68px"
        @submit.native.prevent>
        <el-form-item label="渠道名称" prop="deaName">
          <el-input v-model="queryParamsQd.deaName" placeholder="请输入渠道名称" clearable
            @keyup.enter.native="handleQdQuery" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQdQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQueryQd">重置</el-button>

        </el-form-item>
      </el-form>
      <el-form label-width="80px">
        <el-table v-loading="loading" style="overflow: auto; " height="400px" :data="dealerList"
          @selection-change="handleSelectionChangeQd" @row-click="handleClickTableRowB" ref="fileTableB">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="渠道编号" align="center" prop="deaId" />
          <el-table-column label="渠道名称" align="center" prop="deaName" />
          <el-table-column label="帐号" align="center" prop="deaUser" />
        </el-table>
        <pagination v-show="totalqd > 0" :total="totalqd" :page.sync="queryParamsQd.pageNum"
          :limit.sync="queryParamsQd.pageSize" @pagination="getListDea" />
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="qdClick" v-if="sjbtshow">确 定</el-button>
        <el-button type="primary" @click="gsqdClick" v-if="gsbtshow">确 定</el-button>
        <el-button @click="cancelqd">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import { listallAgreement, getAgreement, delAgreement, addAgreement, updateAgreement } from "@/api/AgreementMain/agreement";
  import { listuser, } from "@/api/system/user";
  import { listDealerAll, } from "@/api/DealerMain/dealer";
  export default {
    name: "Agreement",
    data() {
      return {
        jeform: {},
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 合同表格数据
        agreementList: [],
        // 弹出层标题
        title: "",
        dateRange: [],
        // 是否显示弹出层
        open: false,
        ywyOptions: [],//业务员

        checked: false,


        // 查询参数
        queryParams: {
          agrId: null,
          pageNum: 1,
          pageSize: 20,
          customerId: null,
          deaId: null,
          realDea: null,
          userId: null,
          agrDate: null,
          other1: null,
          other2: null,
          other3: null,
          other4: null,
          other5: null,
          jeDk: null,
          jeBk: null,
          jeFd: null,
          jeFdsj: null,
          jeJfd: null,
          jeJfdsj: null,
          jeLr: null,
          jeLrsj: null,
          jeFk: null,
          jeFq: null,
          jeYfbl: null,
          jeJfbl: null,
          jeNfbl: null,
          khname: null,
          alltype: "0"
        },
        // 表单参数
        form: {},
        // 表单校验
        rules: {
        },

        //分配渠道相关 渠道变量参数
        openqd: false,
        titleqd: "",
        dealerList: [],
        deid: [],//分配选中的渠道
        dename: [],
        qdval: {//分配时，传值的parm
          realDea: null,
          orderId: null,
        },
        totalqd: 0,

        sjbtshow: false,
        gsbtshow: false,
        // 渠道查询参数
        queryParamsQd: {
          pageNum: 1,
          pageSize: 20,
          Dtype: 2,
          deaName: null,

        },

        form2: {
          customerId: null,
          customerIdHw: null,
          khname: null,//客户员名称
          gsname: null,//归属渠道
          sjname: null,//实际渠道
        },
      };
    },
    created() {
      if (this.$route.query.ys != undefined) {
        var ys = this.$route.query.ys;
        this.queryParams.pageNum = parseInt(ys);
      }
      else
        this.queryParams.pageNum = 0;


      this.getList();
      //绑定业务员
      listuser(this.queryParamsUser).then(response => {
        this.ywyOptions = response.rows;
      });
    },
    methods: {
      //保留两位，不足补位
      toFixed(num) {
        return (Math.round(num * 100) / 100).toFixed(2);
      },
      //点击行时跳转
      handle(row, event, column) {
        this.findkh(2, row, this.queryParams.pageNum);
      },

      //跳转到合同页面 - 添加 -修改 传类型参数
      findkh: function (atype, row, pageint) {
        var rid = "";
        if (row != null)
          rid = row.agrId;

        if (this.$store.state.user.userId == 118) {
          
          this.$router.push(
            {
              path: '/htxg/agreementht2',
              methods: 'post',
              query: {
                atype: atype, //表示添加
                did: null,
                aid: rid,//合同id
                ys: pageint,
                searchparms: JSON.stringify(this.queryParams),
                searchdateRange: JSON.stringify(this.dateRange),
              }
            })
        }
        else {
          let routeData = null;
          if (rid.indexOf("BHWY") == -1) {
            routeData = this.$router.resolve({
              path: '/htxg/agreementht2', query: {
                atype: atype, did: null, aid: rid, ys: pageint, searchparms: JSON.stringify(this.queryParams), searchdateRange: JSON.stringify(this.dateRange)
              }
            });
          }
          else {
            routeData = this.$router.resolve({
              path: '/htxg/agreementbight2', query: {
                atype: atype, did: null, aid: rid, ys: pageint, searchparms: JSON.stringify(this.queryParams), searchdateRange: JSON.stringify(this.dateRange)
              }
            });

          }

          window.open(routeData.href, '_blank');
        }
      },
      /** 查询合同列表 */
      getList() {
        this.loading = true;
        listallAgreement(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
          this.agreementList = response.rows;
          console.log(response);
          this.total = response.total;
          this.loading = false;
          if (response.total > 0) {
            this.jeform.amoney = response.rows[0].amoney;
            this.jeform.bmoney = response.rows[0].bmoney;
            this.jeform.cmoney = response.rows[0].cmoney;
          }
          else {
            this.jeform.amoney = "0.00";
            this.jeform.bmoney = "0.00";
            this.jeform.cmoney = "0.00";
          }

        });
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();

      },
      // 表单重置
      reset() {
        this.form = {
          agrId: null,
          customerId: null,
          deaId: null,
          realDea: null,
          userId: null,
          agrDate: null,
          other1: null,
          other2: null,
          other3: null,
          other4: null,
          other5: null,
          jeDk: null,
          jeBk: null,
          jeFd: null,
          jeFdsj: null,
          jeJfd: null,
          jeJfdsj: null,
          jeLr: null,
          jeLrsj: null,
          jeFk: null,
          jeFq: null,
          jeYfbl: null,
          jeJfbl: null,
          jeNfbl: null
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.dateRange = [];
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.agrId)
        this.single = selection.length !== 1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.title = "添加合同";
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        const agrId = row.agrId || this.ids
        getAgreement(agrId).then(response => {
          this.form = response.data;
          this.open = true;
          this.title = "修改合同";
        });
      },
      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.agrId != null) {
              updateAgreement(this.form).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              addAgreement(this.form).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const agrIds = row.agrId || this.ids;
        this.$modal.confirm('是否确认删除合同编号为"' + agrIds + '"的数据项？').then(function () {
          return delAgreement(agrIds);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => { });
      },
      /** 导出按钮操作 */
      handleExport() {
        this.download('AgreementMain/agreement/export', {
          ...this.queryParams
        }, `agreement_${new Date().getTime()}.xlsx`)
      },
      //渠道查询选择相关
      //清空时，执行渠道id赋值
      qk1() {
        this.queryParams.deaId = null;
      },
      qk2() {
        this.queryParams.realDea = null;
      },
      showsjqd(type) {

        if (type == 1) {
          //表示实际渠道
          this.sjbtshow = true;
          this.gsbtshow = false;
          this.titleqd = "选择实际渠道";
        }
        else {
          //表示归属渠道
          this.sjbtshow = false;
          this.gsbtshow = true;
          this.titleqd = "选择归属渠道";
        }

        this.openqd = true;

        this.getListDea();
      },
      /** 查询分配渠道列表 */
      getListDea() {
        this.loading = true;
        listDealerAll(this.queryParamsQd).then((response) => {
          this.dealerList = response.rows;
          this.totalqd = response.total;
          this.loading = false;

        });
      },
      // 分配弹窗多选框选中数据1 渠道
      handleSelectionChangeQd(selection) {
        this.deid = selection.map(item => item.deaId)
        this.dename = selection.map(item => item.deaName)
        this.single = selection.length !== 1
        this.multiple = !selection.length
      },
      cancelqd() {
        this.openqd = false;
        this.reset();
      },
      /** 分配渠道搞操作 */
      qdClick() {
        if (this.deid.length > 1) {
          alert("只能选择一个渠道");
          return;
        }
        this.queryParams.realDea = this.deid[0];
        this.form2.sjname = this.dename[0];
        this.cancelqd();
      },
      gsqdClick() {
        if (this.deid.length > 1) {
          alert("只能选择一个渠道");
          return;
        }
        this.queryParams.deaId = this.deid[0];
        this.form2.gsname = this.dename[0];
        this.cancelqd();
      },
      /**分配渠道窗口重置 */
      resetQueryQd() {
        this.resetForm("queryFormQd");
        this.handleQdQuery();
      },
      handleClickTableRowB(row, event, column) {
        this.$refs.fileTableB.toggleRowSelection(row);
      },
      /** 搜索按钮操作 */
      handleQdQuery() {
        this.getListDea();
      },

      //根据状态修改行字颜色
      tableAddClass({ row, rowIndex }) {
        if (row.dkce != '' && row.dkce != null) {
          if (Number(row.jeNfbl) < 0)
            return "d";
          else
            return "";
        }
        else
          return "";

      },
    },

  };
</script>
<style>
  .el-table th.gutter {
    display: table-cell !important;
    /* 解决表头线未对齐 */
  }
</style>
<style lang="scss">
  // 鼠标经过颜色颜色
  .abc .el-table__body tr:hover>td {
    background-color: #EBF6FF !important;
  }

  //高亮点击事件颜色
  .el-table__body tr.current-row>td {
    background: #EBF6FF !important;
  }
</style>
<!-- /表格颜色 -->
<style scoped>
  .app-container /deep/ .el-table .a {
    color: #13ce66 !important;
  }

  .app-container /deep/ .el-table .b {
    color: #905edf !important;
  }

  .app-container /deep/ .el-table .c {
    color: red !important;
  }

  .app-container /deep/ .el-table .d {
    color: rgb(216, 86, 86) !important;
  }
</style>